﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link rel="stylesheet" type="text/css" href="/Resources/easyui-1.32/themes/default/easyui.css" />
    <link rel="stylesheet" type="text/css" href="/Resources/easyui-1.32/themes/icon.css" />
    <style type="text/css">
        .lockrow
        {
            background-color: #BAD0F7;
        }
        .lockcol
        {
            background-color: #D1E0B2;
        }
        .selected
        {
            background-color: #00FFFF;
        }
        .error{background-color:#FF0000;color:White;}
    </style>
    <script type="text/javascript" src="/Resources/easyui-1.32/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/Resources/easyui-1.32/jquery.easyui.min.js"></script>
    <script type="text/javascript">

        var lockall = false;
        var lockrow = "NULL";
        var lockcolumn = "4,8,9,11";
        var hiddencolumn = "0,1,2,3,5,6,7,12,13";
        var lockcell = "NULL"; //startcol,endcol,startrow,endrow|startcol,endcol,startrow,endrow
        var colwidth = "4,200";
        var hc = "4,6";
        var itype = "number";
        var selectedcellid;
        var selectedcolindex;
        var selectedrowindex;

        function getUrlParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }

        $(document).ready(function () {
            var lastIndex;//new
            $('#tt').datagrid({
                url: 'CommData.aspx?field=t.*,t.rowid&tn=TG03&orderby=ZBBM&year=2011&month=1&dwbm=HB01',
                title: '主要产品产量快报', rownumbers: true, width: 'auto', height: 'auto', fitColumns: true, singleSelect: true, striped: true,

                columns:
                [
                    [{ field: 'NF', title: '年份', rowspan: 1, formatter: function (val, rec) { return unescape(rec.NF); } }, { title: 'NULL', colspan: 0, rowspan: 0 }, { field: 'YF', title: '月份', rowspan: 1, formatter: function (val, rec) { return unescape(rec.YF); } }, { field: 'ZBBM', title: '指标编码', rowspan: 1, formatter: function (val, rec) { return unescape(rec.ZBBM); } }, { field: 'DWBM', title: '单位编码', rowspan: 1, formatter: function (val, rec) { return unescape(rec.DWBM); } }, { field: 'ZBMC', title: '指标名称', rowspan: 1, formatter: function (val, rec) { return unescape(rec.ZBMC); } }, { field: 'ZBDM', title: '指标代码', rowspan: 1, formatter: function (val, rec) { return unescape(rec.ZBDM); } }, { field: 'CJ', title: '层级', rowspan: 1, formatter: function (val, rec) { return unescape(rec.CJ); } }, { field: 'HC', title: '行次', rowspan: 1, formatter: function (val, rec) { return unescape(rec.HC); } }, { field: 'JLDW', title: '计量单位', rowspan: 1, formatter: function (val, rec) { return unescape(rec.JLDW); } }, { field: 'BYSJ', title: '本月实际', rowspan: 1, formatter: function (val, rec) { return unescape(rec.BYSJ); } }, { field: 'BNLJ', title: '本月止累计', rowspan: 1, formatter: function (val, rec) { return unescape(rec.BNLJ); } }, { field: 'QNTQLJ', title: '去年同月止累计', rowspan: 1, formatter: function (val, rec) { return unescape(rec.QNTQLJ); } }, { field: 'LBBM', title: '类别编码', rowspan: 1, formatter: function (val, rec) { return unescape(rec.LBBM); } }, { field: 'ROWID', title: 'Rowid', rowspan: 1, formatter: function (val, rec) { return unescape(rec.ROWID); } }]
                ],
                toolbar: [{
                    text: '新增',
                    iconCls: 'icon-add',
                    handler: function () {
                        //$('#tt').datagrid('acceptChanges');
                        var node = $('#tt').treegrid('getSelected');
                        if (node) {
                            alert('请选择一行');
                        }
                        else {
                            //更新数据   
                            InsertRow();
                        }
                    }
                }, '-', {
                    text: '删除',
                    iconCls: 'icon-cancel',
                    handler: function () {
                        //$('#tt').datagrid('acceptChanges');
                        var node = $('#tt').treegrid('getSelected');
                        if (node) {
                            alert('请选择一行');
                        }
                        else {
                            //删除数据   
                            DeleteRow(node);
                        }
                    }
                }, '-', {
                    text: '保存',
                    iconCls: 'icon-save',
                    handler: function () {
                        //$('#tt').datagrid('acceptChanges');
                        var errorcount = $('.error').length;
                        if (errorcount > 0) {
                            alert('输入数据错误,请检查');
                        }
                        else {
                            //更新数据   
                            SaveData();
                        }
                    }
                }, '-', {
                    text: '上报',
                    iconCls: 'icon-ok',
                    handler: function () {
                        //$('#tt').datagrid('acceptChanges');
                        var errorcount = $('.error').length;
                        if (errorcount > 0) {
                            alert('输入数据错误,请检查');
                        }
                        else {
                            //更新数据   
                            Report();
                        }
                    }
                }, '-', {
                    text: '计算',
                    iconCls: 'icon-reload',
                    handler: function () {
                        //$('#tt').datagrid('acceptChanges');
                        var errorcount = $('.error').length;
                        if (errorcount > 0) {
                            alert('输入数据错误,请检查');
                        }
                        else {
                            //更新数据   
                            Compute();
                        }
                    }
                }, '-', {
                    text: '汇总',
                    iconCls: 'icon-undo',
                    handler: function () {
                        //$('#tt').datagrid('acceptChanges');
                        var errorcount = $('.error').length;
                        if (errorcount > 0) {
                            alert('输入数据错误,请检查');
                        }
                        else {
                            //更新数据   
                            Sum();
                        }
                    }
                }
                ],
                onBeforeLoad: function () {
                    //$(this).datagrid('rejectChanges');
                },
                onClickCell: function (index, field, value) {
                    if (!islock_by_index_field(index, field)) {
                        selectedcellid = getId_by_index_field(index, field);
                        selectedcolindex = get_colindex_byfield(field);
                        selectedrowindex = index;
                        //alert("colindex:"+selectedcolindex+"/rowlindex:"+selectedrowindex);
                        switchtdinput($("#" + selectedcellid));
                    }
                },
                onLoadSuccess: function (val) {
                    setCJ();           //指标层级                    
                    LockC();          //锁定Column
                    LockR();          //锁定Row
                    LockA();         //锁定区域
                    SetStyle();     //设定宽度
                    //HiddenC();    //隐藏Column
                },
            });
        });

        function DeleteRow(node) {
            $.ajax({
                type: 'post',
                url: 'SaveData.aspx',
                data: { data: encodeURIComponent(xml), tn: 'TG03' },
                datatype: 'html',
                success: function (result) { alert('保存成功'); },
                error: function () { alert('发生错误'); },
            });
        }

        //更新数据
        function SaveData() {
            var r = $("tr[changed='1']").length;
            var xml = "<DataRoot>";
            for (var i = 0; i < r; i++) {
                xml += "<Record>";
                var c = $("tr[changed='1']:eq(" + i + ") td").length;
                for (var j = 0; j < c; j++) {
                    var fd = $("tr[changed='1']:eq(" + i + ") td:eq(" + j + ") ").attr("field");
                    xml += "<" + fd + ">"
                    xml += $("tr[changed='1']:eq(" + i + ") td:eq(" + j + ") ").text();
                    xml += "</" + fd + ">";
                }
                xml += "</Record>";
            }
            xml += "</DataRoot>";
            //提交到数据库 
            $.ajax({
                type: 'post',
                url: 'SaveData.aspx',
                data: { data: encodeURIComponent(xml), tn: 'TG03' },
                datatype: 'html',
                success: function (result) { alert('保存成功'); },
                error: function () { alert('发生错误'); },
            });
        }

        function HiddenC() {
            if (hiddencolumn != "NULL" && hiddencolumn != "") {
                var str = hiddencolumn.split(',');
                for (var i = 0; i < str.length; i++) {
                    var f = $('#datagrid-row-r1-2-0 td:eq(' + str[i] + ')').attr("field");
                    $('#tt').datagrid('hideColumn', f);
                }


            }
        }

        function SetStyle() {
            if (colwidth != "NULL" && colwidth != "") {
                var str = colwidth.split('|');
                for (var i = 0; i < str.length; i++) {
                    var m = str[i].split(',');
                    var col = m[0];
                    var width = m[1];
                    var f = $('#datagrid-row-r1-2-0 td:eq(' + col + ')').attr("field");
                    if (f) {
                        $('#tt').datagrid('autoSizeColumn', f); //此处明显降低性能耗时，待优化
                    }
                }
            }
        }

        function LockA() {
            //lock Area
            if (lockcell != "NULL" && lockcell != "") {
                var str = lockcell.split('|');
                for (var i = 0; i < str.length; i++) {
                    xy = str[i].split(',');
                    var x = xy[2];
                    var xspan = xy[1];
                    var y = xy[0];
                    var yspan = xy[3];
                    for (var t = x; t <= yspan; t++) {
                        for (var j = y ; j <= xspan; j++) {
                            var q = $('#datagrid-row-r1-2-' + t + " td:eq(" + j + ")");
                            q.attr("lock", "1");
                            q.addClass("selected");
                        }
                    }
                }
            }
        }

        function LockC() {
            if (lockcolumn != "NULL" && lockcolumn != "") {
                var rows = $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr').length;
                var str = lockcolumn.split(',');
                for (var j = 0; j < str.length; j++) {
                    for (var i = 0; i < rows; i++) {
                        $('#datagrid-row-r1-2-' + i + " td:eq(" + str[j] + ")").attr("lock", "1");
                        //$('#datagrid-row-r1-2-' + i + " td:eq(" + str[j] + ")").addClass("lockcol");
                    }
                }
            }
            if (hiddencolumn != "NULL" && hiddencolumn != "") {
                var rows = $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr').length;
                var str = hiddencolumn.split(',');
                for (var j = 0; j < str.length; j++) {
                    for (var i = 0; i < rows; i++) {
                        $('#datagrid-row-r1-2-' + i + " td:eq(" + str[j] + ")").attr("lock", "1");
                        //$('#datagrid-row-r1-2-' + i + " td:eq(" + str[j] + ")").addClass("lockcol");
                    }
                }
            }
        }

        function LockR() {
            if (lockrow != "NULL") {
                var rows = lockrow.split(',');
                for (var i = 0; i < rows.length; i++) {
                    $('#datagrid-row-r1-2-' + i + " td").attr("lock", "1");
                    $('#datagrid-row-r1-2-' + i + " td").addClass("lockrow");
                }
            }
        }

        function getId_by_index_field(index, field) {
            var id = "datagrid-row-r1-2-" + index + " td[field='" + field + "'] div";
            //$("#"+id).addClass("selected");
            //var rowposition="datagrid-row-r1-2-"+index;
            return id;
        }

        //根据index和field判定单元格是否锁定
        function islock_by_index_field(index, field) {
            var r = $("#datagrid-row-r1-2-" + index + " td[field='" + field + "']").attr("lock");
            if (r == "1")
                return true;
            else
                return false;
        }

        //根据行索引和列索引判定是否锁定
        function islock_by_index(rindex, cindex) {
            var r = $("#datagrid-row-r1-2-" + rindex + " td:eq(" + cindex + ")").attr("lock");
            if (r == "1")
                return true;
            else
                return false;
        }

        var pre = null;
        var inputfomate = "<input type='text' style='padding:0px;'/>";
        var tdinputselection = "";
        var cellislock = "0";

        function switchtdinput(obj) {

            if (pre) {
                doinpleave(pre);
            }
            var width = $(obj).width() * 1.0;
            var objtxt = $.trim($(obj).text());
            $(obj).html($(inputfomate).val(objtxt));
            pre = $(obj).find('input').css("border", "1px solid red").width(width)[0];
            $(obj).find('input').trigger("focus").trigger("select");
            //$(obj).find('input').css("class","easyui-validatebox");
            $(obj).find('input').click(function (event) {
                stopevent(event);
                return false;
            }).blur(function (event) {
                inpleave(event, this);
            }).keypress(function (event) {
                stopevent(event);
            }).keyup(function (event) {
                return setpreornext(event, this);
            }).keydown(function (event) {
                tdinputselection = getSelectedText();
                stopevent(event);
                if (event.ctrlKey && event.keyCode == 86) {

                    //从剪贴板粘贴数据 =========== by xiaovcn
                    var clipText = window.clipboardData.getData('Text');
                    if (clipText != null) {
                        //去除末尾的\r\n以免出现空值 从excel复制默认总是有一个回车 原因?
                        var p = clipText.lastIndexOf(String.fromCharCode(13) + String.fromCharCode(10));
                        if (p != -1) {
                            clipText = clipText.substring(0, p);
                        }
                        //用\r\n分割数据串
                        clipRows = clipText.split(String.fromCharCode(13) + String.fromCharCode(10));

                        for (i = 0; i < clipRows.length; i++) {
                            //用\t分割数据
                            clipRows[i] = clipRows[i].split(String.fromCharCode(9));
                        }
                        //写入html
                        paste(event, this, clipRows);
                    }
                    //从剪贴板粘贴数据 ===========end by xiaovcn
                }
            });

        }

        //根据field获取当前的列索引 
        function get_colindex_byfield(field) {
            var c = "[field='" + field + "']"
            var s = $('.datagrid-header-row td' + c).index();
            return s;
        }

        //根据id返回行索引
        function get_rowindex_byid(obj) {
            return obj.substring(selectedcellid.lastIndexOf('-') + 1)
        }

        //根据行索引和列索引获取jquery选择器 为复制粘贴excel数据
        function get_cell_selector_byindex(r, c) {
            return $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ') td:eq(' + c + ') div')
        }

        //根据行索引和列索引 设置changed=1
        function set_cell_changed(r, c) {
            $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ')').attr('changed', '1');
            $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ') td:eq(' + c + ') div').attr('changed', '1');
        }

        //根据行索引和列索引 移除changed
        function set_cell_Nochanged(r, c) {
            $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ') td:eq(' + c + ') div').removeAttr('changed');
        }

        //粘贴数据
        function paste(event, obj, clipRows) {
            var rindex = selectedrowindex;
            for (i = 0; i < clipRows.length; i++) {
                var cindex = selectedcolindex;
                for (j = 0; j < clipRows[i].length; j++) {
                    //当前位置是input  其他位置 是div
                    var value = clipRows[i][j];

                    //判定当前单元格是否锁定
                    var l = false;
                    l = islock_by_index(rindex, cindex);
                    if (!l) {
                        //设置值
                        get_cell_selector_byindex(rindex, cindex).text(value);
                        set_cell_changed(rindex, cindex);//设置changed属性1
                    }
                    //alert(rindex+"="+cindex);
                    cindex++; //列索引                    
                }
                rindex++; //行索引
            }
        }

        function stopevent(event) {
            event.stopPropagation();
        }

        function inpleave(event, obj) {
            stopevent(event);
            doinpleave(obj);
        }

        function doinpleave(obj) {
            if (!obj) return;
            var val = $(obj).val();
            var $par = $(obj).parent()[0];
            $($par).text(val);
            pre = null;
        }

        function getSelectionStart(o) {
            if (o.createTextRange) {
                var r = document.selection.createRange().duplicate();
                r.moveEnd('character', o.value.length);
                if (r.text == '') return o.value.length
                return o.value.lastIndexOf(r.text);
            } else return o.selectionStart;
        }

        function getSelectedText() {
            if (window.getSelection) {
                return window.getSelection().toString();
            }
            else if (document.getSelection) {
                return document.getSelection();
            }
            else if (document.selection) {
                return document.selection.createRange().text;
            }
        }

        //是否为数字
        function isnum(obj) {
            if (obj == "" || obj == null)
                return true;
            else {
                var re = /^[0-9]+.?[0-9]*$/;
                if (!re.test(obj)) {
                    return false;
                }
                else {
                    return true;
                }
            }
        }



        function setpreornext(event, objThis) {
            // 输入合法性检查
            itype = $(objThis).parent().parent().attr("itype");
            alert(itype);
            $(objThis).parent().parent().parent().attr('changed', 1);
            var inputvalue = $(objThis).val();
            var ck = false;
            if (itype == "number")
                ck = isnum(inputvalue);
            if (ck) {
                //移除error错误提示样式
                $(objThis).parent().parent().removeClass("error");
                var count = -1;
                var current;
                stopevent(event);
                var obj; //焦点移动到得位置
                //判断键盘动作keyCode 40=Down  38=UP  13=enter 37=left  39=right 9=Tab
                if (event.keyCode == 40 || event.which == 40 || event.keyCode == 38 || event.which == 38 || event.keyCode == 13 || event.which == 13 || event.keyCode == 37 || event.which == 37 || event.keyCode == 39 || event.which == 39) {

                    //当前的位置 objThis 为 单元格中的div datagrid-row-r1-2-rowindex
                    row = $(objThis).parent().parent().parent()[0].id;

                    nextrowindex = parseInt(row.substring(row.lastIndexOf('-') + 1)) + 1;

                    prerowindex = parseInt(row.substring(row.lastIndexOf('-') + 1)) - 1;

                    nextrow = row.substring(0, row.lastIndexOf('-') + 1) + nextrowindex;

                    prerow = row.substring(0, row.lastIndexOf('-') + 1) + prerowindex;

                    field = $(objThis).parent().parent().attr("field");

                    //var id="datagrid-row-r1-2-"+index+" td[field='"+field+"'] div";              

                    var downcell = "#" + nextrow + " td[field='" + field + "'] div";
                    var dc_l = "#" + nextrow + " td[field='" + field + "']";

                    var upcell = "#" + prerow + " td[field='" + field + "'] div";
                    var uc_l = "#" + prerow + " td[field='" + field + "']";

                    var thistd = "#" + row + " td[field='" + field + "']";

                    //alert(downcell);
                    //count = parseInt($(objThis).parent().data("i"));

                    var nc = null;

                    if (event.keyCode == 40 || event.which == 40) {
                        obj = $(downcell);//向下    
                        nc = $(dc_l).attr("lock");

                    } else if (event.keyCode == 38 || event.which == 38) {
                        obj = $(upcell);//向上
                        nc = $(uc_l).attr("lock");

                    } else if (event.keyCode == 13 || event.which == 13) {
                        obj = $(downcell);//回车--向下
                        nc = $(dc_l).attr("lock");

                    } else if (event.keyCode == 37 || event.which == 37) {
                        obj = $(thistd).prev("td").find("div");//向左
                        nc = $(thistd).prev("td").attr("lock");

                    } else if (event.keyCode == 39 || event.which == 39) {
                        obj = $(thistd).next("td").find("div");//向右
                        nc = $(thistd).next("td").attr("lock");
                    }
                    if (obj) {

                        //判定要移动目标是否锁定
                        if (nc == "1") {
                            cellislock = "1";
                        }
                        else {
                            cellislock = "0";
                        }
                        if (cellislock == "0") {
                            doinpleave(objThis);
                            switchtdinput(obj);
                        }
                    }
                }

                if (event.keyCode == 13 || event.which == 13)
                    return false;
                else
                    return true;
            }
            else {
                //输入框变色 提示
                $(objThis).parent().parent().addClass("error");
            }
        }


        function setCJ() {
            var hcstr = hc.split(',');
            if (hcstr.length == 2) {
                var r = $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr').length;
                for (var i = 0; i < r; i++) {
                    var str = "";
                    var spacenum = $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + i + ') td:eq(' + hcstr[1] + ') div').text();

                    for (var j = 0; j < spacenum - 1; j++) {
                        str += '&nbsp;';
                    };
                    var txt = str + $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + i + ') td:eq(' + hcstr[0] + ') div').text();
                    $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + i + ') td:eq(' + hcstr[0] + ') div').html(txt);
                }
                //$('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(0)').addClass('lockrow');
            }
        }
    </script>

</head>
<body>
    <div style="padding-bottom:5px; font-size:12px;">
        单位：<select class="easyui-combobox" id="dwbm" name="dwbm" style="width:auto"><option value="HB">华北分公司</option></select>
        时间：<select class="easyui-combobox" id="owner" name="owner" style="width:auto"><option value="2006">2006</option><option value="2007">2007</option><option value="2008">2008</option><option value="2009">2009</option><option value="2010">2010</option><option value="2011">2011</option><option value="2012">2012</option><option value="2013">2013</option><option value="2014">2014</option></select> <select class="easyui-combobox" id="month" name="month" style="width:auto"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option></select>
    </div>
    <table id="tt">
        
    </table>
</body>
</html>
